var syncPanel = new Ext.Panel({
    
    cls: 'syncpanel fullscroll',
    scroll: 'vertical',
    
    dockedItems : [
        {xtype: 'toolbar', dock: 'top',
            items: [
                    {text: 'Connect', handler: dataSync.reconnect},
                    {xtype: 'spacer'},
                    {text: 'Download', handler: dataSync.requestDownload}
            ]
        },
    ],
    
    removeOlds: function(){
        me=syncPanel.items;
        maxCnt=50;
        if (me.getCount()>maxCnt){
            while (me.getCount() > maxCnt)
                me.last().destroy();
            syncPanel.doComponentLayout();
        }
    },

    newNote: function(r, o){
        var me = syncPanel,
            noteData = {
                ts: nowTime(),
                label: o.label,
                status: 'S',
                dowloadSessionId: dataSync.downloadSession.id,
                filterName: o.params.filter
            }
        ;
        
        if (dataSync.downloadSession.id){
            var chunkId =  dataSync.downloadSession.id+'-'+o.params.filter,
                oldNote = me.down('syncnote[chunkId="'+chunkId+'"]')
            ;
        
            if (oldNote){
                oldNote.dataSafe = noteData;
                syncPanel.updateNote(r,o,o.syncNoteId = oldNote.getId(), 'C');
                return;
            }
        }
        
        
        var note = me.insert(0, new SyncNote ({
            xtype: 'syncnote',
            dataSafe: noteData,
            data: [noteData],
            chunkId: dataSync.downloadSession.id+'-'+o.params.filter
        }));
        
        me.doComponentLayout();
        
        o.syncNoteId = note.getId()
        
        me.removeOlds();
        
    },

    successNote: function(r, o){
        o.request.status='D'
        syncPanel.updateNote(r,o)
    },
    
    failureNote: function(r, o){
        o.request.status='F'
        syncPanel.updateNote(r,o)
    },

    updateNote: function(r, o, nId, s, nd){
        me = syncPanel;
        
        if (nId || (nId = o.request.options.syncNoteId)) {
            note = Ext.getCmp(nId);
            note.update(Ext.applyIf({status: s || o.request.status},note.dataSafe));
        }
    }

});

SyncNote = Ext.extend(Ext.Component, {
    cls: 'syncnote',
    tpl: '<tpl for=".">'
            +'<div class="status {status}">{status}</div>'
            +'<div class="ts">{ts}</div>'
            +'<div class="label">{label}</div>'
            +'<div class="measure">{measure}</div>'
         +'</tpl>'
});

Ext.reg('syncnote', SyncNote);


function nowTime() { 
    var now = new Date();
    hh=now.getHours();
    hh=hh>=10?hh:'0'+hh;
    mm=now.getMinutes();
    mm=mm>=10?mm:'0'+mm;
    ss=now.getSeconds();
    ss=ss>=10?ss:'0'+ss;
    
    return hh+':'+mm+':'+ss;
}